<template>
	<view>
		<image src="../../static/me/bg1.jpg" mode="" style="position: fixed;top: 0; left: 0;width: 100vw; height: 100vh;"></image>
		<view style="z-index: 100;position: absolute;width: 100vw;padding: 10px;">
			<view class="list text-center" v-if="userInfo && userInfo.address">
				<text>{{userInfo.address.dorm + userInfo.address.room}}</text>
			</view>
			<view v-if="task" >
				<view class="list">
					叫水人 {{task.publisher}}
				</view>
				<view class="list">
					水票价格 ￥{{userInfo.address.waterPrice}}
				</view>
				<view class="list">
					房间水桶 {{userInfo.address.bucketNum}}
				</view>
				<view class="list">
					剩余水票 {{userInfo.address.ticketNum}}
				</view>
				<view class="list">
					本次叫水 {{task.timestamp}}
				</view>
			</view>
			<view class="list">
				上次换水 {{userInfo.address.lastTime}}
			</view>
			
			<view style="text-align: center; display: flex; align-items: center;">
				<button @click="goToDorimitoryHistory"  type="primary" size="mini" style="margin-right: 10rpx;">
					送水记录
				</button>
				<button v-if="task" @click="cancelTask"  type="warn" size="mini" >取消叫水</button>
				<button v-else @click="addTask" type="primary" size="mini" >现在叫水</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userInfo: null,
			task: null
		};
	},
	onShow() {
		this.userInfo = uni.getStorageSync("userInfo")
		if(!this.userInfo.address){
			uni.showModal({
				content: "还未选择寝室",
				confirmText: '现在去',
				success: function(e){
					if(e.confirm)
						uni.redirectTo({
							url:"/pages/me/dormitory/address"
						})
				}
			})
			return;
		}
		this.getTask();
	},
	methods: {
		// 获取宿舍的送水任务
		getTask() {
			let that = this;
			that.$request('/task/' + that.userInfo.addressId, 'get').then(result => {
				that.task = result.data;
				console.log("[叫水任务信息] " + JSON.stringify(result.data))
				uni.stopPullDownRefresh();
			});
		},
		// 下拉刷新 
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 2000);
			this.getTask();
		},
		// 叫水 发布送水任务
		addTask(){
			let that = this;
			if(that.userInfo.address.ticketNum <= 0){
				that.$msg("房间剩余水票数量不足")
				return;
			}
			that.$request("/task", "post").then(result => {
				that.$msg("成功发布送水任务")
				that.getTask();
			})
		},
		// 取消叫水
		cancelTask(){
			let that = this;
			uni.showModal({
				content: "是否取消该送水任务",
				success: function(e){
					if(e.confirm){
						that.$request("/task/student", "delete", null, errorMsg => {
							that.$msg(errorMsg);
						}).then(result => {
							that.$msg("已取消送水任务")
							that.task = null;
						})
					}
				}
			})
		},
		// 查看送水记录
		goToDorimitoryHistory(){
			uni.navigateTo({
				url: "/pages/me/dormitory/addressTaskHistory?addressId=" + this.userInfo.addressId 
					+ "&addressDetail=" + this.userInfo.address.detail
			})
		}
	}
};
</script>

<style>
	.list{
		margin: 10rpx 0;
		font-size: 40rpx;
	}
</style>
